<template>
  <div>
    <el-form style="width: 60%" :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px"
             class="demo-ruleForm">
      <el-form-item label="学生姓名" prop="sname">
        <el-input v-model="ruleForm.sname" :value="ruleForm.sname"></el-input>
      </el-form-item>
      <el-form-item label="初始密码" prop="password">
        <el-input v-model="ruleForm.password" :value="ruleForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'editorStudent',
  data () {
    return {
      ruleForm: {
        sid: null,
        sname: null,
        password: null
      },
      rules: {
        sname: [
          {
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          },
          {
            min: 2,
            max: 5,
            message: '长度在 2 到 5 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          {
            required: true,
            message: '请输入密码',
            trigger: 'change'
          }
        ],
      }
    }
  },
  created () {

    let id = this.$route.query.sid || 1
    axios.get('http://localhost:9000/student/findById/' + id).then(res => {
      this.ruleForm = res.data
    })
  },
  methods: {
    submitForm (formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          axios.put('http://localhost:9000/student/updateStudent',this.ruleForm).then(res => {
            if (res.data) {
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              });
            } else {
              this.$message({
                showClose: true,
                message: '修改失败',
                type: 'error'
              });
            }
            this.$router.push("/studentList")
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm (formName) {
      this.$refs[formName].resetFields();
    },
  }
}
</script>

<style scoped>

</style>
